﻿using System.Dynamic;
using System.Xml.Linq;

namespace Eff4.Data.Xml
{
    /// <summary>
    /// xml构造器
    /// 使用方法：
    /// XElement xml =
    ///             b.persons(
    ///             b.person("Tom", age: 10),
    ///             b.person("Jerry", age: 8));
    /// 生成xml：
    /// <persons>
    ///     <person age="10">Tom</person>
    ///     <person age="8">Jerry</person>
    /// </persons>
    /// </summary>
    public class XmlMarkupBuilder : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder,
    object[] args, out object result)
        {
            var xml = new XElement(binder.Name);
            var attrCount = binder.CallInfo.ArgumentNames.Count;
            var elementCount = args.Length - attrCount;
            for (int i = 0; i < elementCount; i++)
            {
                xml.Add(args[i]);
            }
            for (var i = 0; i < attrCount; i++)
            {
                var attrName = binder.CallInfo.ArgumentNames[i];
                if (attrName[0] == '@') attrName = attrName.Substring(1);
                xml.Add(new XAttribute(attrName, args[i + elementCount]));
            }
            result = xml;
            return true;
        }
    }
}
